package com.zyj.exam_app.question_manager.service.impl;

import com.zyj.exam_app.question_manager.bean.QuestionBean;
import com.zyj.exam_app.question_manager.mapper.QuestionMapper;
import com.zyj.exam_app.question_manager.service.QuestionService;
import com.zyj.exam_app.testPaper_manager.bean.TestPaperBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class QuestionServiceImpl implements QuestionService{
    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public List<QuestionBean> findAllQuestions() {
        return questionMapper.findAllQuestions();
    }

    @Override
    public boolean addOneQuestion(QuestionBean question) {
        //参数校验

        //保存
        return questionMapper.insertOneQuestion(question) == 1;
    }

    @Override
    public boolean deleteOneQuestionById(String questionId) {
        if(StringUtils.isBlank(questionId)){
            //这里可以抛出异常，提示没有指定要删除的数据

            return true;
        }
        questionMapper.deleteOneQuestionById(questionId);
        return true;
    }

    @Override
    public List<QuestionBean> randomSelectionQuestion(int num, String type) {
        //参数校验

        //查询试题
        List<QuestionBean> questionList = questionMapper.selectQuestionsByType(type);
        int total = questionList.size();
        if(total <= num){
            //题库中题数不足，则全部抽取
            return questionList;
        }

        //抽取试题
        List<QuestionBean> selectedQuestions = new ArrayList<>();
        int step = total / num;
        int initialNum = (int) (Math.random() * step);
        for(int i = 0; i < num; i++){
            selectedQuestions.add(questionList.get(initialNum));
            initialNum += step;
        }
        return selectedQuestions;
    }
}
